package cn.catsdad.auth.aspect;

import cn.catsdad.auth.annotation.log.Log;
import cn.catsdad.auth.util.SecurityUtil;
import cn.catsdad.constant.iConstant.IDateFormat;
import cn.catsdad.dto.UserDTO;
import cn.catsdad.util.DateUtil;
import cn.catsdad.util.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuyonglong
 * @version V1.0 2023/12/12
 */
@Aspect
@Component
public class LogAspect {

    private static final Map<String, Logger> loggerMap = new ConcurrentHashMap<>();

    @Pointcut(value = "@annotation(cn.catsdad.auth.annotation.log.Log)")
    public void log() {
    }

    @AfterReturning("log()")
    public void doAfter(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            MethodSignature targetMethodSign = (MethodSignature) signature;
            Method targetMethod = targetMethodSign.getMethod();
            Log logAnnotation = targetMethod.getAnnotation(Log.class);
            String loggerName = logAnnotation.logType().getLoggerName();
            Logger logger = getLogger(loggerName);
            if (logger != null) {
                StringBuilder msg = new StringBuilder().append("操作模块名：")
                        .append(logAnnotation.moduleName()).append(" 操作类型：")
                        .append(logAnnotation.operationType().getName()).append(" 操作说明：")
                        .append(logAnnotation.description());
                UserDTO user = SecurityUtil.getUser();
                if (user != null) {
                    msg.append(" 操作人员：").append(user.getUserName());
                }
                msg.append(" 操作时间：").append(DateUtil.now(IDateFormat.YYYY_MM_DD_HH_MM_SS));
                logger.info(msg.toString());
            }
        }
    }

    private Logger getLogger(String loggerName) {
        Logger result = null;
        if (StringUtil.isNotEmpty(loggerName)) {
            result = loggerMap.get(loggerName);
        }
        if (result == null) {
            result = LoggerFactory.getLogger(loggerName);
            if (result != null) {
                loggerMap.put(loggerName, result);
            }
        }
        return result;
    }

}
